package tld.course.lesson2 
{
	import flash.display.BitmapData;
	import flash.display.Graphics;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	/**
	 * ...
	 * @author wvxvw
	 */
	public class Canvas
	{
		public function set grid(value:Grid):void { this._grid = value; }
		
		public function set snake(value:Snake):void { this._snake = value; }
		
		private var _graphics:Graphics;
		private var _grid:Grid;
		private var _snake:Snake;
		private var _cellSize:uint;
		
		public function Canvas(graphics:Graphics) 
		{
			super();
			this._graphics = graphics;
		}
		
		public function update(cellSize:uint):void
		{
			var width:uint = this._grid.width;
			var height:uint = this._grid.height;
			var size:uint;
			var length:uint = height * cellSize;
			
			this._cellSize = cellSize;
			this._graphics.clear();
			this._graphics.lineStyle(1, 0x808080, 1, true);
			while (width-- > 0)
			{
				size = width * cellSize;
				this._graphics.moveTo(size, 0);
				this._graphics.lineTo(size, length);
			}
			width = this._grid.width;
			length = width * cellSize;
			while (height-- > 0)
			{
				size = height * cellSize;
				this._graphics.moveTo(0, size);
				this._graphics.lineTo(length, size);
			}
			this.drawSnake();
			this._grid.eachFood(this.drawFood);
		}
		
		private function drawSnake():void
		{
			var cell:Point;
			
			this._snake.reset();
			this._graphics.beginFill(0);
			while (cell = this._snake.next())
				this._graphics.drawRect(
					cell.x * this._cellSize, 
					cell.y * this._cellSize, 
					this._cellSize, 
					this._cellSize);
			this._graphics.endFill();
		}
		
		private function drawFood(foodKind:uint, index:uint):void
		{
			this._graphics.beginFill(0xFF00);
			this._graphics.drawRect(
				uint(index % this._grid.width) * this._cellSize,
				uint(index / this._grid.width) * this._cellSize,
				this._cellSize,
				this._cellSize);
			this._graphics.endFill();
		}
	}
}